package com.xingtu.serialportdemo

import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.SystemClock
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ObjectUtils
import com.blankj.utilcode.util.ToastUtils
import com.xingtu.serialportdemo.adapter.TextListAdapter
import kotlinx.android.synthetic.main.activity_main.*
import tp.xmaihh.serialport.SerialHelper
import tp.xmaihh.serialport.bean.ComBean
import tp.xmaihh.serialport.stick.AbsStickPackageHelper
import tp.xmaihh.serialport.utils.ByteUtil
import java.io.IOException
import java.nio.charset.StandardCharsets


class MainActivity : AppCompatActivity() {


    private var serialHelper: SerialHelper? = null
    private var isHexType = false
    private var text = ""

    private val mHandler = Handler { msg ->
        when (msg.what) {
            -1 -> {
                ToastUtils.showLong("关闭串口")
            }
            else -> {
                val comBean = msg.obj as ComBean
                val time = comBean.sRecTime
                var rxText: String
                rxText = String(comBean.bRec, StandardCharsets.UTF_8)
                if (isHexType) {
                    //转成十六进制数据
                    rxText = ByteUtil.ByteArrToHex(comBean.bRec)
                }
                text += "Rx-> $time: $rxText\r\n"
                //                et_read_content.text =(text)
                //                scrollview.smoothScrollTo(0,et_read_content.bottom)
                //                //        LogUtils.e("text=" + text)
            }
        }


        false
    }

    lateinit var context: Context
    lateinit var listAdapter: TextListAdapter
    var strList = ArrayList<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        context = this
        recyclerView.layoutManager = LinearLayoutManager(context)
        listAdapter = TextListAdapter(strList)
        recyclerView.adapter = listAdapter


        initSerialConfig()
        //初始化信息要在open之间进行
        openInit()
        rg_type.setOnCheckedChangeListener { radioGroup, id ->
            when (id) {
                R.id.rb_txt -> {
                    isHexType = false
                    bt_send.text = "txt 发送"
                }
                R.id.rb_hex -> {
                    isHexType = true
                    bt_send.text = "HEX 发送"
                }
            }
        }

    }

    private fun initSerialConfig() {
        //初始化SerialHelper对象，设定串口名称和波特率（此处为接收扫码数据）
        serialHelper = object : SerialHelper("/dev/ttyS2", 115200) {
            override fun onDataReceived(paramComBean: ComBean) {
                runOnUiThread {
                    kotlin.run {
                        if (ObjectUtils.isNotEmpty(serialHelper) && serialHelper?.isOpen==true){
                            val time = paramComBean.sRecTime
                            var rxText: String
                            rxText = String(paramComBean.bRec, StandardCharsets.UTF_8)
                            if (isHexType) {
                                //转成十六进制数据
                                rxText = ByteUtil.ByteArrToHex(paramComBean.bRec)
                            }
                            var text = "Rx-> $time: $rxText\r\n"
                            LogUtils.e(text)
                            listAdapter.addData(text)
                            if (ObjectUtils.isNotEmpty(listAdapter)) {
                                recyclerView.smoothScrollToPosition(listAdapter.data.size)
                            }
                        }
                        //                        text += "Rx-> $time: $rxText\r\n"
                    }
                }
                //                val message = mHandler.obtainMessage()
                //                message.obj = paramComBean
                //                //                LogUtils.json(LogUtils.E, message.obj)
                //                var rxText = String(paramComBean.bRec)
                //                LogUtils.e(rxText)
                //                mHandler.sendMessage(message)
            }
        }

        /*
         * 默认的BaseStickPackageHelper将接收的数据扩展成64位，一般用不到这么多位
         * 我这里重新设定一个自适应数据位数的
         */
        serialHelper!!.stickPackageHelper = AbsStickPackageHelper {
            try {
                val available = it.available()
                if (available > 0) {
                    val buffer = ByteArray(available)
                    val size = it.read(buffer)
                    if (size > 0) {
                        return@AbsStickPackageHelper buffer
                    }
                } else {
                    SystemClock.sleep(100)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
            null
        }


    }

    fun openInit() {
        try {
            if (ObjectUtils.isNotEmpty(serialHelper) && serialHelper!!.isOpen) {
                LogUtils.e("串口已打开")
                //TODO 给串口发数据才能 返回精确的数据
                var cmd = "com,com1,115200\r\n"
                var bytes = cmd.toByteArray()
                LogUtils.e(cmd, bytes)
                serialHelper?.baudRate = 115200
                serialHelper?.sendTxt(cmd)
                Thread.sleep(100)

                cmd = "com,com1,115200\r\n"
                bytes = cmd.toByteArray()
                LogUtils.e(cmd, bytes)
                serialHelper?.baudRate = 57600
                serialHelper?.sendTxt(cmd)
                Thread.sleep(100)

                cmd = "com,com1,115200\r\n"
                bytes = cmd.toByteArray()
                LogUtils.e(cmd, bytes)
                serialHelper?.baudRate = 38400
                serialHelper?.sendTxt(cmd)
                Thread.sleep(100)


                cmd = "com,com1,115200\r\n"
                serialHelper?.baudRate = (19200)
                bytes = cmd.toByteArray()
                LogUtils.e(cmd, bytes)
                serialHelper?.sendTxt(cmd)
                Thread.sleep(100)

                cmd = "com,com1,115200\r\n"
                serialHelper?.baudRate = (9600)
                bytes = cmd.toByteArray()
                LogUtils.e(cmd, bytes)
                serialHelper?.sendTxt(cmd)
                Thread.sleep(100)

                serialHelper?.baudRate = (115200)
                cmd = "saveconfig\r\n"
                bytes = cmd.toByteArray()
                LogUtils.e(cmd, bytes)
                serialHelper?.sendTxt(cmd)

                cmd = "unlog\r\n"
                serialHelper?.sendTxt(cmd)
                LogUtils.e(cmd, bytes)
                Thread.sleep(100)

                cmd = "CONFIG NMEA0183 V41\r\n"
                serialHelper?.baudRate = (115200)
                LogUtils.e(cmd, bytes)
                serialHelper?.sendTxt(cmd)
                Thread.sleep(100)

                cmd = "GPGGA com1 0.1\r\n"
                LogUtils.e(cmd, bytes)
                serialHelper?.sendTxt(cmd)
                Thread.sleep(100)

                cmd = "GPRMC com1 0.1\r\n"
                LogUtils.e(cmd, bytes)
                serialHelper?.sendTxt(cmd)
                Thread.sleep(100)
                cmd = "HeadingA com1 0.1\r\n"
                LogUtils.e(cmd, bytes)
                serialHelper?.sendTxt(cmd)
                Thread.sleep(100)
                cmd = "GPZDA com1  10\r\n"
                LogUtils.e(cmd, bytes)
                serialHelper?.sendTxt(cmd)
                Thread.sleep(100)
                cmd = "saveconfig\r\n"
                LogUtils.e(cmd, bytes)
                serialHelper?.sendTxt(cmd)
                Thread.sleep(100)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun onclick(view: View) {
        when (view.id) {
            R.id.bt_open -> {
                if (serialHelper?.isOpen == true) {
                    Toast.makeText(this, "串口已经打开", Toast.LENGTH_SHORT).show()
                    return;
                }
                try {

                    serialHelper?.open()
                } catch (e: Exception) {

                }

            }
            R.id.bt_close -> {
                try {
                    if (ObjectUtils.isNotEmpty(serialHelper) && serialHelper?.isOpen==true) {
                        serialHelper?.close()
                        Toast.makeText(this, "串口关闭", Toast.LENGTH_SHORT).show()
                    }
                } catch (e: java.lang.Exception) {

                }

            }
            R.id.bt_clear_content -> {
                strList.clear()
                listAdapter.notifyDataSetChanged()
            }
            R.id.bt_send -> {
                if (!serialHelper!!.isOpen) {
                    Toast.makeText(this, "串口没打开 发送失败", Toast.LENGTH_SHORT).show()
                    return
                }
                if (isHexType) {
                    serialHelper!!.sendHex(et_send_content.editableText.toString())
                } else {
                    serialHelper!!.sendTxt(et_send_content.editableText.toString())
                }
                LogUtils.e("发送")
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (serialHelper != null) {
            serialHelper!!.close()
        }
        serialHelper = null
    }
}